@using System.Timers
@using BlazorApp.Service.k8s
@using k8s.Models
<Bullet Config="_uiConfig"/>

@code {

    [Inject] public INodeService NodeService { get; set; }

    [Parameter] public V1Node Node { get; set; }

    [Inject] private IMetricsService MetricsService { get; set; }

    private bool _isMetricsServerReady;
    private BulletConfig _uiConfig;
    private Timer _timer;

    protected override async Task OnInitializedAsync()
    {
        _isMetricsServerReady = await MetricsService.MetricsServerReady();

        _timer = new Timer(10000);
        _timer.Elapsed += async (sender, eventArgs) => await OnTimerCallback();
        _timer.Start();
        _uiConfig = GetConfig();
        await base.OnInitializedAsync();
    }

    private async Task OnTimerCallback()
    {
        _uiConfig = GetConfig();
        await InvokeAsync(StateHasChanged);
    }

    private int CalcMeasure(string fullValue)
    {
        var strings = fullValue.Split("/");
        var s1 = strings[0];
        var s2 = strings[1];
        if (string.IsNullOrWhiteSpace(s1))
        {
            s1 = "0";
        }

        if (string.IsNullOrWhiteSpace(s2))
        {
            s1 = "1";
        }

        var avg = Math.Round((double.Parse(s1) / double.Parse(s2)), 2);
        return (int)(avg * 100);
    }

    BulletConfig GetConfig()
    {
        var nodeName = Node.Name();
        var podCapacity = NodeService.GetPodCapacity(nodeName);
        var cpuCapacity = NodeService.GetCpuCapacity(nodeName);
        var memoryCapacity = NodeService.GetMemoryCapacity(nodeName);

        BulletConfig config = new BulletConfig()
        {
            Data = new BulletViewConfigData[]
            {
                new BulletViewConfigData
                {
                    Title = "Pods (%)",
                    Measures = new[] { CalcMeasure(podCapacity) },
                    Targets = new[] { 85 },
                    Ranges = new double[] { 25, 50, 75, 100 },
                },
                new BulletViewConfigData
                {
                    Title = "CPU (%)",
                    Measures = new[] { CalcMeasure(cpuCapacity) },
                    Targets = new[] { 85 },
                    Ranges = new double[] { 25, 50, 75, 100 },
                },
                new BulletViewConfigData
                {
                    Title = "Memory (%)",
                    Targets = new[] { 85 },
                    Measures = new[] { CalcMeasure(memoryCapacity) },
                    Ranges = new double[] { 25, 50, 75, 100 },
                }
            },
            Width = 300,
            Height = 150,
            RangeMax = 100,
            TargetField = "target",
            RangeField = "ranges",
            MeasureField = "measures",
            XField = "title",
            RangeColors = new string[] { "#64DAAB", "#6595FA", "#FF9D4F", "#D62A0E" },
        };
        return config;
    }

}
